package com.jason.quectel;

import java.io.*;
import java.util.Date;

/**
 * @author：Jason
 * @date：2022/3/7 21:19
 * @email：1129847330@qq.com
 * @description:
 */
public class Food implements Serializable {
    private static final long serialVersionUID = 42L;
    public String name;
    public transient String date;
    public int num;

    @Override
    public String toString() {
        return "Food{" + "name='" + name + '\'' + ", date='" + date + '\'' + ", num=" + num + '}';
    }

    public static void main(String[] args) {
        Food food = new Food();
        food.date = new Date().toString();
        food.name = "大米饭";
        food.num = 1;
        writeObject(food);
        System.out.println(readObject().toString());
    }

    private static <T> void writeObject(T t) {
        try {
            File file = new File("./food.ser");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(t);
            objectOutputStream.close();
            fileOutputStream.close();
            System.out.println("对象写入成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Object readObject() {
        try {
            FileInputStream fileInputStream = new FileInputStream("./food.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            Object food = objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();
            return food;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}